#!/usr/bin/env ruby
require 'erb'

$: <<  ENV['PANNONICA_HOME']
require 'pannonica'

ENV['APPLICATION_HOME'] = Dir.pwd

require 'session'
require 'app'
require 'lib/pidfile'

# for profiling
# require 'profile'

def exit_if_running
  with_pidfiles do |pfs|
    entries = pfs.map{|ea| "#{ea.filename} (#{ea.pid})"}
    puts 'cluster seem to be running already'
    puts "found these pid files:\n  #{entries.join("\n  ")}"
    exit -1
  end
end

if ARGV.size != 3
  puts "usage: samples.sh hostname port processes"
  exit -1
else
  hostname = ARGV[0]
  base_port = ARGV[1].to_i
  processes = (1..ARGV[2].to_i).to_a
  if processes.size == 0
    # zero in the sense zero daemons
    Application::start(hostname, base_port)
  else
    exit_if_running
    cwd = Dir.pwd
    processes.to_a.each_with_index do |_, i|
      port = base_port + i
      task = Daemons.call(:multiple=> true) do
        Dir.chdir(cwd)
        Application::start(hostname, port)
      end
      pid = task.pid.pid
      puts "started server #{hostname}:#{port} (pid: #{pid})"
      File.open("log/app_#{port}.pid",'w') { |fh|
        fh.write("#{pid}\n")
      }
    end
  end
end
